import { Module } from 'vuex'
import type { TRootState } from '../type'
import type { TThemeState } from './type'

import localCache from '@/utils/cache'

const ThemeModule: Module<TThemeState, TRootState> = {
  namespaced: true,
  state() {
    return {
      bcColor: '#5292fe',
      fontColor: '#fff',
      defaultColors: [
        '#fff',
        '#FF5C8A',
        '#FF7A9E',
        '#717FF9',
        '#4791EB',
        '#39AFEA',
        '#2BB669',
        '#6ACC19',
        '#E2AB12',
        '#FF8F57',
        '#FD726D',
        '#FD544E'
      ]
    }
  },
  getters: {},
  mutations: {
    updateBcColor(state, index) {
      state.bcColor = state.defaultColors[index]
      if (index === 0) {
        state.fontColor = '#000'
        return
      }
      state.fontColor = '#fff'
    },
    updateColor(state, color) {
      state.bcColor = color
      if (color === 'rgba(255,255,255,1)') {
        state.fontColor = '#000'
        return
      }
      state.fontColor = '#fff'
    }
  },
  actions: {
    loadLocalTheme({ commit, state }) {
      const defalutI = localCache.getCache('defalutTheme')
      if (!defalutI && defalutI !== 0) {
        localCache.setCache('defalutTheme', 3)
        localCache.setCache('defalutColor', null)
      } else if (defalutI < state.defaultColors.length) {
        commit('updateBcColor', localCache.getCache('defalutTheme'))
        return false
      }
      const dColor = localCache.getCache('defalutColor')
      if (dColor) {
        localCache.setCache('defalutTheme', 99)
        localCache.setCache('defalutColor', dColor)
        commit('updateColor', localCache.getCache('defalutColor'))
      }
    }
  }
}
export default ThemeModule
